package com.itheima.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.Util.JwtUtil;
import com.itheima.dao.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * 登录过滤器,进行登录token拦截
 */
@Slf4j
//@Component
public class LoginFilter implements Filter {
    @Resource
    EmpMapper empMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("初始化过滤器");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("开始执行http请求过滤");
        //参数向下转型成HttpServletRequest和HttpServletResponse对象
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //防止中文乱码
        servletResponse.setContentType("application/json;charset=UTF-8");
        //放行登录接口
        String requestURI = request.getRequestURI();
        if (requestURI.contains("login")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断token是否为空 -> 是否绕过登录
        if (Objects.isNull(token)){
            //设置响应码401
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            PrintWriter writer = servletResponse.getWriter();
            Result fail = Result.fail("请先登录");
            //使用fastjson把对象转成json字符串
            String jsonString = JSONObject.toJSONString(fail);
            writer.write(jsonString);
            return;
        }
        //使用jwt工具类验证token是否合法
        try {
            JSONObject jsonObject = JwtUtil.checkToken(token);
            Emp login = empMapper.login(jsonObject.getString("username"));
            if(Objects.isNull(login) || !login.getPassword().equals(jsonObject.getString("password"))){
                //设置响应码401(未经授权的)
                //response.setStatus(401);
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                Result fail = Result.fail("token无效或过期");
                String jsonString = JSONObject.toJSONString(fail);
                PrintWriter writer = servletResponse.getWriter();
                writer.write(jsonString);
                return;
            }
        //若捕获到异常说明token不合法
        } catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            Result fail = Result.fail("token无效或过期");
            String jsonString = JSONObject.toJSONString(fail);
            PrintWriter writer = servletResponse.getWriter();
            writer.write(jsonString);
            return;
        }
        //过滤链对象执行完过滤逻辑后放行http请求,把 request和 response对象重新交给 controller(servlet)
        filterChain.doFilter(servletRequest,servletResponse);
        log.info("过滤完成");
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
